import React, { createContext, useContext, useEffect, useState, useRef } from 'react';
import { useLocation } from 'react-router-dom';

interface TimerState {
  isRunning: boolean;
  isPaused: boolean;
  timeLeft: number;
  currentTimer: any;
  startTime: number;
  pausedTime: number;
}

interface BackgroundTimerContextType {
  timerState: TimerState;
  startTimer: (timer: any, isWorkSession?: boolean) => void;
  pauseTimer: () => void;
  resumeTimer: () => void;
  stopTimer: () => void;
  updateTimer: (timeLeft: number) => void;
  isBackgroundActive: boolean;
}

const BackgroundTimerContext = createContext<BackgroundTimerContextType | null>(null);

export const useBackgroundTimer = () => {
  const context = useContext(BackgroundTimerContext);
  if (!context) {
    throw new Error('useBackgroundTimer must be used within BackgroundTimerProvider');
  }
  return context;
};

interface BackgroundTimerProviderProps {
  children: React.ReactNode;
  settings?: any;
}

export const BackgroundTimerProvider: React.FC<BackgroundTimerProviderProps> = ({ children, settings }) => {
  const location = useLocation();
  const [timerState, setTimerState] = useState<TimerState>({
    isRunning: false,
    isPaused: false,
    timeLeft: 0,
    currentTimer: null,
    startTime: 0,
    pausedTime: 0
  });
  
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const lastActiveTimeRef = useRef<number>(Date.now());

  // 检查是否在Focus页面
  const isOnFocusPage = location.pathname === '/focus';

  // 启动计时器
  const startTimer = (timer: any, isWorkSession: boolean = true) => {
    const duration = isWorkSession ? timer.work_duration : timer.break_duration; // 根据阶段选择正确的duration
    setTimerState({
      isRunning: true,
      isPaused: false,
      timeLeft: duration,
      currentTimer: timer,
      startTime: Date.now(),
      pausedTime: 0
    });
  };

  // 暂停计时器
  const pauseTimer = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    
    setTimerState(prev => ({
      ...prev,
      isRunning: false,
      isPaused: true,
      pausedTime: Date.now()
    }));
  };

  // 恢复计时器
  const resumeTimer = () => {
    setTimerState(prev => ({
      ...prev,
      isRunning: true,
      isPaused: false,
      pausedTime: 0
    }));
  };

  // 停止计时器
  const stopTimer = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    
    setTimerState({
      isRunning: false,
      isPaused: false,
      timeLeft: 0,
      currentTimer: null,
      startTime: 0,
      pausedTime: 0
    });
  };

  // 更新计时器时间
  const updateTimer = (timeLeft: number) => {
    setTimerState(prev => ({
      ...prev,
      timeLeft
    }));
  };

  // 计时器逻辑
  useEffect(() => {
    if (timerState.isRunning && !timerState.isPaused) {
      intervalRef.current = setInterval(() => {
        setTimerState(prev => {
          const newTimeLeft = prev.timeLeft - 1;
          
          if (newTimeLeft <= 0) {
            // 计时器结束
            if (intervalRef.current) {
              clearInterval(intervalRef.current);
              intervalRef.current = null;
            }
            
            // 注意：声音和通知处理已移至FocusMode组件中，避免重复处理
            
            return {
              ...prev,
              isRunning: false,
              timeLeft: 0
            };
          }
          
          return {
            ...prev,
            timeLeft: newTimeLeft
          };
        });
      }, 1000);
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [timerState.isRunning, timerState.isPaused]);

  // 页面可见性变化处理
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.hidden) {
        // 页面隐藏时记录时间
        lastActiveTimeRef.current = Date.now();
      } else {
        // 页面显示时，如果计时器在运行，需要调整时间
        if (timerState.isRunning && !timerState.isPaused) {
          const hiddenTime = Date.now() - lastActiveTimeRef.current;
          const adjustedTimeLeft = Math.max(0, timerState.timeLeft - Math.floor(hiddenTime / 1000));
          
          setTimerState(prev => ({
            ...prev,
            timeLeft: adjustedTimeLeft
          }));
        }
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [timerState.isRunning, timerState.isPaused, timerState.timeLeft]);

  const isBackgroundActive = timerState.isRunning && !isOnFocusPage;

  return (
    <BackgroundTimerContext.Provider
      value={{
        timerState,
        startTimer,
        pauseTimer,
        resumeTimer,
        stopTimer,
        updateTimer,
        isBackgroundActive
      }}
    >
      {children}
    </BackgroundTimerContext.Provider>
  );
};

export default BackgroundTimerProvider;